package org.example.weboj.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Utility class for password encryption
 */
public class PasswordUtil {
    
    /**
     * Encrypts a password using MD5
     * 
     * @param password the plain text password
     * @return the MD5 hash of the password
     */
    public static String encryptPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(password.getBytes());
            
            StringBuilder hexString = new StringBuilder();
            for (byte b : messageDigest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Error encrypting password", e);
        }
    }
    
    /**
     * Verifies if a password matches its hash
     * 
     * @param password the plain text password to verify
     * @param hash the stored hash to compare against
     * @return true if the password matches the hash, false otherwise
     */
    public static boolean verifyPassword(String password, String hash) {
        String encryptedPassword = encryptPassword(password);
        return encryptedPassword.equals(hash);
    }
} 